<?php

namespace app\admin\controller;

use app\common\controller\publics\Jwt;
use think\Controller;
use think\Db;
use think\facade\Cache;
use think\Request;

class Caches extends Controller
{
    public function initialize()
    {
        error_reporting(5);//1+4
        //设置跨域头
        header('Access-Control-Allow-Origin: *');
        //token 验证登录信息是否有效
        $request = new Request();
        $g=$request->get();
        $p=$request->post();
        $token = '';
        (isset($g['token']) && !empty($g['token'])) and ($token = $g['token']);
        (isset($p['token']) && !empty($p['token'])) and ($token = $p['token']);
        if(empty($token)){
            js_code('
                    var str = localStorage.getItem("token");
                    if(str !=="" || str.length>0){
                        var preg = /(\?token=.*|\?.*)/i
                        var href = location.href.replace(preg,"");
                        location.href=(href+"?token="+localStorage.getItem("token")).replace(/[?]{2,}/g,"?");
                    }else{
                        location.href="/admin_login_out";
                    }   
           ');
        }
        $jwt = new \app\common\controller\publics\Jwt();
        if(!($this->token = $jwt->is_token($token)) || empty(cookie('fwf_admin_name'))){
            $this->error('信息验证错误，请重新登录','/admin_login_out');
        }
    }


    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
    }

    //缓存列表
    public function cache_list(){
        //检查权限
        power_check();
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::tag('menu')->get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);

        $this->assign('title',lang('cache_list'));
        $cache_list = Db::table('fwf_cache')->alias('c')->field('c.*,m.menu_title,m.menu_name')
            ->leftJoin('fwf_menu m','c.cache_menu_id = m.menu_id')
            ->select();

        $this->assign('cache_list',$cache_list);
        return $this->fetch();
    }
    //添加，修改缓存信息
    public function cache_edit(Request $request){
        //检查权限
        power_check();
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::tag('menu')->get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);

        $id = $request->param('id');
        $admin_id = cookie('fwf_admin_id');
        $t = lang('cache_add');
        if($id){
            $t = lang('cache_edit');
        }
        $this->assign('title',$t);

        $cache_list = Db::name('cache')->where('cache_pid','=',0)->select();
        $menu_list = Db::name('menu')->where('menu_pid','in',[43])->whereOr('menu_id','=',43)->select();
        $cache = Db::name('cache')->where('cache_id','=',$id)->find();

        $this->assign('cache_list',$cache_list);
        $this->assign('menu_list',$menu_list);
        $this->assign('cache',$cache);
        return $this->fetch();
    }
    //保存缓存信息
    public function cache_save(Request $request){
        //检查权限
        power_check();

        $p = $request->post();
        $admin_id = cookie('fwf_admin_id');
        $id = $p['cache_id'];
        $validate = new \app\admin\validate\Caches();
        if(!$validate->scene('cache_save')->check($p)){
            $err = $validate->getError();
            $this->error(array_shift($err));
        }else{
            $data = [
                'cache_pid'         => $p['cache_pid'],
                'cache_param'       => $p['cache_param'],
                'cache_menu_id'     => $p['cache_menu_id'],
                'cache_key'         => $p['cache_key'],
                'cache_pre'         => $p['cache_pre'],
                'cache_name'        => $p['cache_name'],
                'cache_desc'        => $p['cache_desc'],
            ];
            if($id){
                //修改
                $up_n = Db::name('cache')->where('cache_id','=',$id)->data($data)->update();
                if($up_n){
                    fwf_log('修改缓存信息，修改的ID：'.$id.'，操作管理员id：'.$admin_id.'，影响的行数：'.$up_n);
                }
                $this->success(lang('edit_success'),'/caches/cache_edit/id/'.$id.'/?token='.$p['token']);
            }else{
                //添加
                $insert_id = Db::name('cache')->insertGetId($data);
                if ($insert_id){
                    fwf_log('添加缓存信息，添加的ID：'.$insert_id.'，操作管理员id：'.$admin_id);
                    $this->success(lang('add_success'),'/caches/cache_list/?token='.$p['token']);
                }
                $this->error(lang('add_fail'),'/caches/cache_list/?token='.$p['token']);
            }
        }
    }
    //删除缓存信息
    public function cache_del(Request $request){
        //检查权限
        power_check();
        $id = $request->param('id');
        if($id){
            $del_n = Db::name('cache')->where('cache_id','=',$id)->delete();
            if($del_n){
                fwf_log('删除缓存记录，删除的ID：'.$id.'，操作管理员id：'.cookie('fwf_admin_id').'，删除的行数：'.$del_n);
                $this->redirect('/caches/cache_list/');
            }
        }
        $this->error(lang('del_fail'));
    }




    public function article(Request $request){

    }
    //前台头部菜单信息缓存操作
    public function home_top_menu(Request $request){
        $param = $request->param();
        $g = $request->get();
        $id = $param['id'];
        $del = $param['del'];
        $cache = Db::name('cache')->where('cache_id','=',$id)->find();
        if($cache){
            if($del !=1){
                //获取头部导航栏信息
                $this->top_menu = Db::name('config')->where('config_desc','=','top_menu')->where('config_pid','<>',0)->order(['config_order'=>'desc'])->select();
                $GLOBALS['tree']['pid'] = 'config_pid';
                $GLOBALS['tree']['id'] = 'config_id';
                $this->top_menu = get_tree($this->top_menu);
                set_leval($this->top_menu);
                if(!empty($cache['cache_pre'])){
                    Cache::tag($cache['cache_pre'])->set($cache['cache_key'],$this->top_menu);
                }else{
                    Cache::set($cache['cache_key'],$this->top_menu);
                }
                $this->success('更新缓存成功','/Caches/cache_list/?token='.$g['token']);
            }else{
                Cache::rm($cache['cache_key']);
                $this->success('删除缓存成功','/Caches/cache_list/?token='.$g['token']);
            }

        }else{
            $this->error('操作错误！','/Caches/cache_list/?token='.$g['token']);
        }
    }
}
